<template>
  <form class="source-upload-wrapper" @submit.prevent>
    <div class="title-wrapper wrapper">
      <h2 class="w1">标题:</h2>
      <div class="title-input-wrapper w2">
        <input type="text" v-model="title">
      </div>
    </div>

    <div class="cover-wrapper wrapper">
      <h2 class="w1">封面:</h2>
      <cover-upload class="cover-upload w2"
      ref="coverUpload"
      ></cover-upload>
    </div>

    <div class="file-wrapper wrapper">
      <h2 class="w1">文件:</h2>
      <div class="file-input-wrapper w2">
        <div class="cover">
          <i v-show="!fileIcon">upload</i>
          <img :src="fileIcon" alt="FILE"
          v-show="fileIcon">
        </div>
        <input type="file" name="file" id="file"
        ref="fileInput" @input="handleFileInput($event.target.files[0])">
      </div>
    </div>

    <div class="abstract-wrapper wrapper">
      <h2 class="w1">摘要:</h2>
      <text-area class="abstract-input w2"
      :maxlength="1000"
      v-model:value="digest"
      ></text-area>
    </div>

    <div class="type-wrapper wrapper">
      <h2 class="w1">分类:</h2>
      <type-list class="type-list w2"
      :types="typeNames" v-model:typeSelect="typeSelect"></type-list>
    </div>

    <div class="tag-wrapper wrapper">
      <h2 class="w1">资源标签:</h2>
      <tag-list class="tag-list w2"
      :tags="pubTags"
      @addTag="addTag"
      @delTag="delTag"
      ></tag-list>
    </div>

    <!-- <div class="original-wrapper wrapper">
      <h2 class="w1">是否原创</h2>
      <div class="w2">
        <input type="radio" value="origin" name="original" id="original"
        v-model="original">
        <label for="original">原创</label>
        <input type="radio" value="reprint" name="original" id="reprint"
        v-model="original">
        <label for="reprint">转载</label>
      </div>
    </div> -->

    <div class="submit-wrapper">
      <button class="submit" @click.prevent="pubSource" ref="submitBtn">发布</button>
      <button class="store" @click.prevent="storeSource" ref="storeBtn">存草稿</button>
    </div>
  </form>
</template>

<script>
import { mapState } from 'vuex';

import TextArea from '@c/utils/Input/TextArea.vue';
import TypeList from '../utils/TypeList.vue';
import TagList from '../utils/TagList.vue';
import CoverUpload from '../utils/CoverUpload.vue';

  export default {
    components: {
      TextArea,
      TypeList,
      TagList,
      CoverUpload
    },
    data() {
      return {
        title: '',
        typeSelect: [],
        original: 'origin',
        digest: '',
        file: null,
        fileIcon: '',
        pubTags: [],
      }
    },
    computed: {
      ...mapState(['typeNames', 'tagNames']),
      draftId() {
        let id = parseInt(this.$route.query.draftId);
        if(isNaN(id)) id = undefined;
        return id;
      }
    },
    methods: {
      addTag(tag) {
        if(this.pubTags.includes(tag)) {
          this.$alert('标签已经添加！');
        } else {
          this.pubTags.push(tag);
        }
      },
      delTag(idx) {
        this.pubTags.splice(idx, 1);
      },

      pubSourceWithData(data) {
        this.$refs.submitBtn.disabled = true;
        this.$confirm("确认发布？").then(flag => {
          if(flag) {
            this.$parent.pubSource(data).then(res => {
              if(res.data.success) {
                this.$alert("发布成功").then(() => {
                  this.$open('/');
                });
              } else {
                this.$alert({
                  type: 'error',
                  content: '发布失败'
                });
                this.$refs.submitBtn.disabled = false;
              }
            }).catch(error => {
              this.$alert({
                type: 'error',
                content: '发布失败'
              });
              this.$refs.submitBtn.disabled = false;
            })
          } else {
            this.$refs.submitBtn.disabled = false;
          }
        })
      },  
      pubSource() {
        if(!this.$refs.coverUpload.checkCover()) {
          this.$alert({
            type: 'error',
            content: '请上传封面'
          });
          return;
        }
        if(this.typeSelect.every(e => !e)) {
          this.$alert({
            type: 'error',
            content: '请选择分类'
          });
          return;
        }
        if(!this.file) {
          this.$alert({
            type: 'error',
            content: '请上传文件'
          });
          return;
        }
        if(this.file.size / 1024 / 1024 > 200) {
          this.$alert({
            type: 'error',
            content: '暂不支持200M以上大文件'
          });
          return;
        }
        this.cover = this.$refs.coverUpload.getCover();
        if(this.cover) {
          this.$compressImage(this.cover).then(res => {
            this.cover = res;
            let data = {
              cover: this.cover,
              title: this.title,
              file: this.file,
              tag: this.pubTags.join(','),
              type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
              original: this.original === 'origin' ? 1 : 0,
              digest: this.digest
            }
            this.pubSourceWithData(data);
          })
        } else {
          this.pubSourceWithData({
            title: this.title,
            file: this.file,
            tag: this.pubTags.join(','),
            type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
            original: this.original === 'origin' ? 1 : 0,
            digest: this.digest
          });
        }
      },

      storeSourceWithData(data) {
        this.$refs.storeBtn.disabled = true;
        if(this.draftId) {
          this.$confirm("是否覆盖旧草稿？").then(flag => {
            if(flag) {
              this.$parent.updateSourceDraft(data).then(res => {
                if(res.data.success) {
                  this.$alert("保存成功");
                } else {
                  this.$alert({
                    type: 'error',
                    content: '保存失败'
                  });
                  this.$refs.storeBtn.disabled = false;
                }
              })
            } else {
              this.$parent.storeSource(data).then(res => {
                if(res.data.success) {
                  this.$alert("保存成功");
                } else {
                  this.$alert({
                    type: 'error',
                    content: '保存失败'
                  });
                  this.$refs.storeBtn.disabled = false;
                }
              })
            }
          })
        } else {
          this.$parent.storeSource(data).then(res => {
            if(res.data.success) {
              this.$alert("保存成功");
            } else {
              this.$alert({
                type: 'error',
                content: '保存失败'
              });
              this.$refs.storeBtn.disabled = false;
            }
          })
        }
      },
      storeSource() {
        let file = this.file;
        if(file instanceof File && file.size > this.$chunkSize) {
          this.$alert({
            type: 'error',
            content: '5MB以上文件不支持保存草稿，请直接发布'
          });
          return;
        }
        this.cover = this.$refs.coverUpload.getCover();
        if(this.cover) {
          this.$compressImage(this.cover).then(res => {
            this.cover = res;
            let data = {
              draft_id: this.draftId,
              cover: this.cover,
              title: this.title,
              file: this.file,
              tag: this.pubTags.join(','),
              type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
              original: this.original === 'origin' ? 1 : 0,
              digest: this.digest
            };
            this.storeSourceWithData(data);
          })
        } else {
          let data = {
            draft_id: this.draftId,
            title: this.title,
            file: this.file,
            tag: this.pubTags.join(','),
            type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
            original: this.original === 'origin' ? 1 : 0,
            digest: this.digest
          }
          this.storeSourceWithData(data);
        }
      },

      autoStoreSourceWithData(data) {
        if(this.draftId) {
          this.$parent.updateSourceDraft(data).then(res => {
            if(res.data.success) {
              this.$alert("保存成功");
            } else {
              this.$alert({
                type: 'error',
                content: '保存失败'
              });
              this.$refs.storeBtn.disabled = false;
            }
          })
        } else {
          this.$parent.storeSource(data).then(res => {
            if(res.data.success) {
              this.$alert("保存成功");
              this.$router.push({
                path: this.$route.path,
                query: res.data.object
              })
            } else {
              this.$alert({
                type: 'error',
                content: '保存失败'
              });
              this.$refs.storeBtn.disabled = false;
            }
          })
        }
      },
      autoStoreSource() {
        let file = this.file;
        if(file instanceof File && file.size > this.$chunkSize) {
          this.$alert({
            type: 'error',
            content: '5MB以上文件不支持保存草稿，请直接发布'
          });
          return;
        }
        this.cover = this.$refs.coverUpload.getCover();
        if(this.cover) {
          this.$compressImage(this.cover).then(res => {
            this.cover = res;
            let data = {
              draft_id: this.draftId,
              cover: this.cover,
              title: this.title,
              file: this.file,
              tag: this.pubTags.join(','),
              type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
              original: this.original === 'origin' ? 1 : 0,
              digest: this.digest
            };
            this.autoStoreSourceWithData(data);
          })
        } else {
          let data = {
            draft_id: this.draftId,
            title: this.title,
            file: this.file,
            tag: this.pubTags.join(','),
            type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
            original: this.original === 'origin' ? 1 : 0,
            digest: this.digest
          }
          this.autoStoreSourceWithData(data);
        }
      },

      handleFileInput(file) {
        console.log('handle file input');
        if(file) {
          this.file = file;
          this.fileIcon = this.$getFileIcon(file.name);
        }
      },
      fillDraft(draft) {
        this.draftId = draft.id;
        this.title = draft.title;
        this.$refs.coverUpload.fillCoverByUrl(draft.cover);
        this.original = draft.original ? 'origin' : 'reprint';
        this.digest = draft.digest;
        let typeSelect = new Array(this.typeNames.length);
        this.typeNames.forEach((type, idx) => {
          if(draft.type.includes(type)) typeSelect[idx] = true;
        });
        this.typeSelect = typeSelect;
        this.pubTags = draft.tag;
        fetch(this.$baseURL + draft.file).then(res => {
          res.blob().then(blob => {
            let filename = this.$file.getFileName(draft.file)
            this.file = new File([blob], filename);
            this.fileIcon = this.$getFileIcon(filename);
          })
        })
      },
      clear() {
        this.title = '';
        this.$refs.coverUpload.clear();
        this.file = null;
        this.fileIcon = '';
        this.digest = '';
        this.typeSelect.fill(false);
        this.pubTags = [];
      }
    },
    mounted () {
      document.addEventListener('keydown', event => {
        if(event.ctrlKey && event.key === 's') {
          event.preventDefault();
          this.autoStoreSource();
        }
      });
    },
  }
</script>

<style lang="less" scoped>
@w: var(--sourceUploadWidth);

.source-upload-wrapper {
  box-sizing: border-box;
  width: @w;
  background-color: white;
  padding: calc(@w * 0.05) calc(@w * 0.08);
  --w1: calc(@w * 0.15);
  --w2: calc(@w - var(--w1) - @w * 0.16);

  .w1, .w2 {
    float: left;
  }

  .w1 {
    width: var(--w1);
  }

  .w2 {
    width: var(--w2);
  }

  .wrapper {
    --lh: calc(@w * 0.03);

    &:not(:first-child) {
      margin-top: calc(@w * 0.04);
    }

    h2 {
      font-size: calc(@w * 0.017);
      line-height: var(--lh);
    }

    &::after {
      content: "";
      display: block;
      clear: both;
    }
  }

  .title-wrapper > .title-input-wrapper {
    --h: calc(@w * 0.05);

    box-sizing: border-box;
    border: 1px solid var(--gray);
    border-radius: calc(var(--h) * 0.1);

    transition: .2s;

    &:focus-within {
      border-color: var(--lightBlue);
    }

    overflow: hidden;

    input {
      width: 90%;
      height: var(--h);
      line-height: var(--h);

      font-size: calc(var(--h) * 0.4);

      padding-left: calc(var(--h) * 0.5);
    }
  }

  .cover-wrapper > .cover-upload {
    --coverUploadWidth: var(--w2);
    --coverUploadLineHeight: var(--lh);
  }

  .file-wrapper > .file-input-wrapper {
    --w: calc(var(--w2) * 0.2);
    --h: calc(var(--w2) * 0.13);
    position: relative;
    width: var(--w);
    height: var(--h);

    input {
      width: var(--w);
      height: var(--h);
      opacity: 0;
      position: absolute;
      top: 0;
      left: 0;

      &:hover {
        cursor: pointer;
      }
    }

    .cover {
      position: relative;
      width: var(--w);
      height: var(--h);
      line-height: var(--h);
      text-align: center;
      border-radius: calc(var(--w) * 0.05);
      border: 1px dashed var(--gray);
      color: var(--gray);

      img {
        width: calc(var(--w) * 1.05);
        height: calc(var(--h) * 1.05);
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    &:hover .cover {
        color: var(--blue);
        border-color: var(--blue);
    }
  }

  .abstract-wrapper {
    .abstract-input {
      --textAreaWidth: var(--w2);
      --textAreaHeight: calc(var(--w2) * 0.2);
    }
  }

  .type-wrapper > .type-list {
    --typeListWidth: var(--w2);
    --typeListLineHeight: var(--lh);
  }

  .tag-wrapper > .tag-list {
    --tagListWidth: var(--w2);
    --tagListLineHeight: var(--lh);
  }

  // .cover-wrapper > .cover-upload {
  //   --coverUploadWidth: var(--w2);
  //   --coverUploadLineHeight: var(--lh);
  // }

  .original-wrapper {
    .w2 {
      line-height: var(--lh);

      input:not(:first-child) {
        margin-left: calc(var(--lh) * 2);
      }

      label {
        margin-left: calc(var(--lh) * 0.5);
      }
    }
  }

  .submit-wrapper {
    margin-top: calc(@w * 0.01);
    text-align: right;

    .submit,
    .store {
      padding: calc(@w * 0.01) calc(@w * 0.03);
      font-size: calc(@w * 0.02);
      font-weight: bold;
      border-radius: calc(@w * 0.005);
      background-color: var(--bodyBg);
      color: var(--darkBlue);

      &:hover {
        background-image: linear-gradient(-200deg, #fac0e7, #91baff);
        color: white;
      }
    }
  }
}
</style>